package 集合.求差异;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

import jdk8.User;

public class 解析WebAndDbList {
    public static void main(String[] args) {
        User u1 = new User(1, "u1");
        User u2 = new User(2, "u2");
        User u3 = new User(3, "u3");
        User u4 = new User(4, "u4");
        //來自web端页面的集合
        List<User> webList = Arrays.asList(u1, u2, u3);
        //来自数据的list
        List<User> dbList = Arrays.asList(u1, u2, u4);
        CompareListRes<User> compareList = CompareList(webList, dbList, User::getId);
        System.out.println("要删除的。。" + compareList.getDeleteList());
        System.out.println("要插入的。。" + compareList.getInsertList());
    }


    public static <E, T> CompareListRes<E> CompareList(Collection<E> webList, Collection<E> dbList, Function<? super E, ? extends T> keyMapper) {
        webList = Optional.ofNullable(webList).orElse(Collections.emptyList());
        dbList = Optional.ofNullable(dbList).orElse(Collections.emptyList());
        CompareListRes<E> res = new CompareListRes<>();
        Map<? extends T, E> mweb = webList.stream().collect(Collectors.toMap(keyMapper, Function.identity()));
        Map<? extends T, E> mdb = dbList.stream().collect(Collectors.toMap(keyMapper, Function.identity()));
        res.setDeleteList(Optional.ofNullable(dbList.stream().filter(d -> !mweb.containsKey(keyMapper.apply(d))).collect(Collectors.toList())).orElse(Collections.emptyList()));
        res.setInsertList(Optional.ofNullable(webList.stream().filter(w -> !mdb.containsKey(keyMapper.apply(w))).collect(Collectors.toList())).orElse(Collections.emptyList()));
        return res;
    }
}
